import React from 'react'
import {connect} from 'dva'
import {Table, Form, Input, Select, Button, Modal, Popconfirm, message} from 'antd';
import RightBox from "../../../components/commons/RightBox";
import RightContacts from "../../../utils/RightConstants";
const FormItem = Form.Item;
const R = require('ramda');

const sprNameNoNeed = ['bankCode'];

const BusinessParams = ({routes, params, children, location, dispatch, businessParams}) => {
    const {page, search, list, editModel, codeList} = businessParams;

    const formItemLayout = {
        labelCol: {
            xs: {span: 120},
            sm: {span: 60},
        },
        wrapperCol: {
            xs: {span: 120},
            sm: {span: 60},
        },
    };

    const columns = [{
        title: '业务参数类型',
        dataIndex: 'sprDesc',
        key: 'sprDesc',
    }, {
        title: '参数名称',
        dataIndex: 'sprName',
        key: 'sprName',
    }, {
        title: '参数值',
        dataIndex: 'sprValue',
        key: 'sprValue',
    }, {
        title: '状态',
        render(record) {
                return (
                    record.isEnabled == 1 ? "启用" : "停用"
                );
        }
    }, {
        title: '操作',
        render(record) {

            let editParamButton=<RightBox resource={RightContacts.BASEDATA.BASE_BUSINESS_EDIT}>
                     <a href="#" onClick={
                        () => {
                            dispatch({
                                type: 'businessParams/getBusinessParamsById',
                                payload: {
                                    sprCode : record.sprCode,
                                    sprName : record.sprName
                                }
                            })
                        }
                    }>编辑</a>
                    <span className="ant-divider"/>
                </RightBox>;
            let deleteParamButton=<RightBox resource={RightContacts.BASEDATA.BASE_BUSINESS_DELETE}>
                <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={() => {
                    dispatch({
                        type: 'businessParams/deleteBusinessParamsById',
                        payload: {
                            sprCode : record.sprCode,
                            sprName : record.sprName
                        }
                    });
                }} okText="是" cancelText="否">
                    <a href="#">删除</a>
                </Popconfirm>
            </RightBox>;
            return (
                <span>
                    {editParamButton}
                    {deleteParamButton}
                </span>
            );
        }
    }];

    const handleAdd = function () {
        dispatch({
            type: 'businessParams/setEditModel',
            payload: {
                showStatus: true,
                title: '创建业务参数',
                type: 'add',
                form: {
                    sprCode: '',
                    sprName: '',
                    sprValue: '',
                    sprSortWeights: '',
                    sprDesc: '',
                    isEnabled: ''
                }
            }
        });
    }

    const SearchForm = Form.create()(({form}) => {
        const {getFieldDecorator, validateFields} = form;

        const handleSearch = function () {
            validateFields((errors, values) => {
                if (errors) {
                    return
                }

                dispatch({
                    type: 'businessParams/setSearch', payload: {
                        search: {
                            sprCode: values.sprCode,
                            status: values.status
                        }
                    }
                });
                let newPage = page;
                newPage.page = 1;
                dispatch({
                    type: 'businessParams/setPage', payload: {
                        page: newPage
                    }
                });
                dispatch({type: 'businessParams/getBusinessParamsList'});
            });
        }
            let addParamButton=<RightBox resource={RightContacts.BASEDATA.BASE_BUSINESS_ADD}><Button icon="plus" onClick={handleAdd}>添加业务参数</Button></RightBox>;
        return (

            <div>
                <Form layout="inline" style={{marginBottom: 15}}>

                    <FormItem
                        {...formItemLayout}
                        label="业务参数类型"
                        hasFeedback
                    >
                        {getFieldDecorator('sprCode', {
                            initialValue: search.sprCode == undefined ? "" : search.sprCode
                        })(
                            <Select style={{width:112}} >
                                {
                                    !R.isNil(codeList) ? codeList.map(item => {
                                        return (<Select.Option value={item.spr_code} key={item.spr_code}>{item.spr_desc}</Select.Option>);
                                    }) : ''
                                }
                            </Select>
                        )}
                    </FormItem>

                    <Button type="primary" icon="search" style={{marginRight: 5}} onClick={handleSearch}>查询</Button>
                    {addParamButton}
                </Form>
            </div>
        );

    });

    return (
        <div>
            <EditBusinessParams visible={editModel.showStatus} title={editModel.title} confirmLoading={editModel.confirmLoading}
                        dispatch={dispatch} editModel={editModel} codeList={codeList}/>

            <SearchForm/>

            <Table rowKey={record => {return (record.sprCode + record.sprName)}} dataSource={list} columns={columns} bordered={false} size={'middle'} pagination={{
                showTotal: total => `共 ${total} 条数据`,
                pageSize: page.size,
                total: page.totalRow,
                showSizeChanger: true,
                current: page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = page;
                    newPage.size = size;
                    newPage.page = 1;
                    dispatch({
                        type: 'businessParams/setPage', payload: {
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = page;
                    newPage.page = pageNumber;
                    dispatch({
                        type: 'businessParams/setPage', payload: {
                            page: newPage
                        }
                    });
                    dispatch({type: 'businessParams/getBusinessParamsList'});
                }
            }}/>
        </div>

    );


}

const EditBusinessParams = ({visible, title, editModel, dispatch, confirmLoading, codeList}) => {

    const formItemLayout = {
        labelCol: {
            xs: {span: 24},
            sm: {span: 6},
        },
        wrapperCol: {
            xs: {span: 24},
            sm: {span: 14},
        },
    };


    let xform = editModel.form;
    const WrappedForm = Form.create()(({form}) => {
        const {getFieldDecorator, validateFields, getFieldValue} = form;
        if(xform.sprCode === 'serviceBank' || getFieldValue('sprCode') === 'serviceBank'){
            title = <span style={{color: 'red'}}>{"银企直连的参数属性必须对应的银行代码保持一致"}</span>;
        }
        function setSprDesc(value,option) {
            xform.sprDesc = option.props.children;
        }

        return (
            <Modal visible={visible} title={title} maskClosable={false} confirmLoading={confirmLoading} onCancel={
                () => {
                    dispatch({
                        type: 'businessParams/setEditModel',
                        payload: {
                            showStatus: false
                        }
                    });
                }
            } onOk={
                () => {
                    validateFields({ force: true }, (errors, values) => {
                        if (errors) {
                            return
                        }

                        if (editModel.type === "add") {
                            dispatch({
                                type: 'businessParams/addBusinessParams',
                                payload: {
                                    sprCode: values.sprCode,
                                    sprName: values.sprName,
                                    sprValue: values.sprValue,
                                    sprSortWeights: values.sprSortWeights,
                                    sprDesc: values.sprDesc,
                                    isEnabled: values.isEnabled
                                }
                            });
                        } else {
                            dispatch({
                                type: 'businessParams/updateBusinessParams',
                                payload: {
                                    sprCode: values.sprCode,
                                    sprName: values.sprName,
                                    sprValue: values.sprValue,
                                    sprSortWeights: values.sprSortWeights,
                                    sprDesc: values.sprDesc,
                                    isEnabled: values.isEnabled
                                }
                            });
                        }
                    });
                }
            }>

                <Form>
                    <FormItem
                        {...formItemLayout}
                        label="业务参数类型"
                        hasFeedback
                    >
                        {getFieldDecorator('sprCode', {
                            rules: [{
                                required: true, message: '请选择业务参数类型',
                            }],
                            initialValue: xform.sprCode
                        })(
                            <Select  onSelect={setSprDesc} disabled = {editModel.type !== "add"}> 
									{
										!R.isNil(codeList) ? codeList.map(item => {
											return (<Select.Option value={item.spr_code} key={item.spr_code}>{item.spr_desc}</Select.Option>);
										}) : ''
									}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="参数名称"
                        hasFeedback
                    >
                        {getFieldDecorator('sprName', {
                            rules: [{
                                required: !R.contains(form.getFieldValue("sprCode"), sprNameNoNeed), message: '请输入参数名称',
                            }],
                            initialValue: xform.sprName
                        })(
                            <Input disabled={R.contains(form.getFieldValue("sprCode"), sprNameNoNeed)} maxLength="60"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="参数值"
                        hasFeedback
                    >
                        {getFieldDecorator('sprValue', {
                            rules: [{
                                required: true, message: '请输入参数值',
                            }],
                            initialValue: xform.sprValue
                        })(
                            <Input  maxLength="30"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="状态"
                        hasFeedback
                    >
                        {getFieldDecorator('isEnabled', {
                            rules: [{
                                required: true, message: '请输入状态',
                            }],
                            initialValue: xform.isEnabled == '' ?  '1' : xform.isEnabled
                        })(
                            <Select>
                                <Option value="1">启用</Option>
                                <Option value="0">停用</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator('sprDesc', {
                            initialValue: xform.sprDesc
                        })(
                            <Input type='hidden' maxLength="120"/>
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    });


    return (
        <WrappedForm/>
    );
}

export default connect(({businessParams}) => ({businessParams}))(BusinessParams)
